package whf.framework.report.jasper;

import java.io.File;
import java.io.OutputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.util.JRProperties;
import whf.framework.config.ApplicationConfig;
import whf.framework.log.Log;
import whf.framework.log.LogFactory;
import whf.framework.report.ReportConstants;
import whf.framework.report.ReportExportHandler;
import whf.framework.report.ReportExporter;
import whf.framework.report.ReportFactory;
import whf.framework.report.ReportUtils;
import whf.framework.util.Utils;

/**
 * @author wanghaifeng
 * @create Dec 14, 2006 2:37:18 PM
 * 
 */
public class JasperExportHandler implements ReportExportHandler {
	private static Log log = LogFactory.getLog(JasperExportHandler.class);
	/**
	 * 编译临时目录
	 * @property String:compilerTempDir
	 */
	private String compilerTempDir;
	
	public void handle(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String reportType = request.getParameter(ReportConstants.EXPORT_TYPE);
		try {
			ReportExporter exporter = ReportFactory.getInstance().getReportExporter(reportType);
			exporter.setReportDescriptor(ReportUtils.getReportDescriptor());
			OutputStream os = response.getOutputStream();
			exporter.exportReport(os);
			os.flush();
		} catch (Exception ex) {
			log.error(this, ex);
			throw ex;
		}
	}

	public void init(ServletContext context) throws ServletException {
		this.compilerTempDir = context.getRealPath(ApplicationConfig.getInstance().getValue(ReportConstants.EXPORT_FILES));
		File file = new File(this.compilerTempDir);
		if(file.exists() && file.isFile()){
			throw new ServletException("The specify dir is not a validate dir!");
		}
		if(!file.exists()){
			Utils.mkdir(this.compilerTempDir);
		}
		//
		JRProperties.setProperty(JRProperties.COMPILER_CLASSPATH, context.getRealPath("/WEB-INF/lib/jasperreports-1.0.1.jar")
				+ System.getProperty("path.separator") + context.getRealPath("/WEB-INF/classes/"));

		JRProperties.setProperty(JRProperties.COMPILER_TEMP_DIR, this.compilerTempDir);
	}

}